package com.kingmed.kmss.framework.feign.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.kingmed.kmss.common.utils.JsonUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 内部feign调用拦截器，自动添加header
 */
@Slf4j
@Component
public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        log.info("Feign 调用, url: {} ", requestTemplate.request().url());

        HttpServletRequest request = Optional.ofNullable(RequestContextHolder.getRequestAttributes()).map(it -> ((ServletRequestAttributes) it).getRequest()).orElse(null);
        if (request == null) {
            return;
        }
        if (CollectionUtil.isEmpty(requestTemplate.headers().get(HttpHeaders.AUTHORIZATION))) {
            //当内部调用feign接口时，请求header的Authorization为空，则放入当前用户的token（内部请求）
            //当外围系统调用feign接口时，原则上需要传Authorization,request为空时还是取接口调用填写的AUTHORIZATION（外部请求）
            //StpUtil.getTokenValue()=调用接口时填写的AUTHORIZATION，会抛出异常
            requestTemplate.header(HttpHeaders.AUTHORIZATION, StpUtil.getTokenValue());
        }

        log.info("feign header:{}", JsonUtils.toJsonString(requestTemplate.headers()));
    }

}
